# 为了方便，将channels和key放在一个命名空间里
from utils.key import is_valid_redis_key, get_all_keys
from redisData.rServer import RS
import websockets
import asyncio

from redisStrcut.redis_struct import RedisClient



def check_channel_key(channel_key, rClient):
    all_keys = get_all_keys(rClient)
    if channel_key in all_keys:
        if all_keys[channel_key] != "channel":
            return "(error) WRONGTYPE Operation against a key holding the wrong kind of value"


def publish(cmd_list, rClient):
    channel_data = RS.rDB[rClient.redisDbId].pubsub_channels
    cmd_list.pop(0)
    if len(cmd_list) >= 2:
        all_keys = get_all_keys(rClient)
        key = cmd_list[0]
        if is_valid_redis_key(key):
            cmd_list.pop(0)
            check_channel_key(key, rClient)
            if key not in all_keys:
                tmp = []
                for i in range(len(cmd_list)):
                    tmp.append(cmd_list[i])
                channel_data[key] = tmp
                return "(integer)" + str(len(tmp))
            else:
                tmp = channel_data[key]
                for i in range(len(cmd_list)):
                    tmp.append(cmd_list[i])
                channel_data[key] = tmp
                return "(integer)" + str(len(tmp))
        else:
            return "(error)Invalid key"
    else:
        return "(error) ERR wrong number of arguments for 'publish' command "


def subscribe(cmd_list, rClient):
    channel_data = RS.rDB[rClient.redisDbId].pubsub_channels
    cmd_list.pop(0)
    if len(cmd_list) == 1:
        all_keys = get_all_keys(rClient)
        key = cmd_list[0]
        if is_valid_redis_key(key):
            cmd_list.pop(0)
            check_channel_key(key, rClient)
            if key not in all_keys:
                return "(error)the channel do not exist"
            else:
                tmp = ' '.join(channel_data[key])
                return tmp
        else:
            return "(error)Invalid key"
    else:
        return "(error) ERR wrong number of arguments for 'subscribe' command "
